package certificate

import (
	"gitee.com/enlangs/goautocert/internal/models"
	"gitee.com/enlangs/goautocert/internal/modules/logger"
	"gitee.com/enlangs/goautocert/internal/modules/utils"
	"gitee.com/enlangs/goautocert/internal/routers/base"
	"gopkg.in/macaron.v1"
	"strconv"
)

// Index Certificate 列表
func Index(ctx *macaron.Context) string {
	cert := new(models.Certificate)
	queryParams := parseQueryParams(ctx)
	total, err := cert.Total(queryParams)
	if err != nil {
		logger.Error(err)
	}
	hosts, err := cert.List(queryParams)
	if err != nil {
		logger.Error(err)
	}

	jsonResp := utils.JsonResponse{}

	return jsonResp.Success(utils.SuccessContent, map[string]interface{}{
		"total": total,
		"data":  hosts,
	})
}

// All 获取所有 Certificate
func All(ctx *macaron.Context) string {
	cert := new(models.Certificate)
	cert.PageSize = -1
	hosts, err := cert.List(models.CommonMap{})
	if err != nil {
		logger.Error(err)
	}

	jsonResp := utils.JsonResponse{}

	return jsonResp.Success(utils.SuccessContent, hosts)
}

// Detail Certificate详情
func Detail(ctx *macaron.Context) string {
	cert := new(models.Certificate)
	id := ctx.ParamsInt(":id")
	err := cert.Find(id)
	jsonResp := utils.JsonResponse{}
	if err != nil || cert.Id == 0 {
		logger.Errorf("获取Certificate详情失败#Certificateid-%d", id)
		return jsonResp.Success(utils.SuccessContent, nil)
	}

	return jsonResp.Success(utils.SuccessContent, cert)
}

// Remove 删除Certificate
func Remove(ctx *macaron.Context) string {
	id, err := strconv.Atoi(ctx.Params(":id"))
	json := utils.JsonResponse{}
	if err != nil {
		return json.CommonFailure("参数错误", err)
	}

	cert := new(models.Certificate)
	err = cert.Find(int(id))
	if err != nil {
		return json.CommonFailure("Certificate不存在")
	}

	_, err = cert.Delete(id)
	if err != nil {
		return json.CommonFailure("操作失败", err)
	}

	return json.Success("操作成功", nil)
}

// 解析查询参数
func parseQueryParams(ctx *macaron.Context) models.CommonMap {
	var params = models.CommonMap{}
	params["Id"] = ctx.QueryInt("id")
	params["Email"] = ctx.QueryTrim("email")
	base.ParsePageAndPageSize(ctx, params)

	return params
}
